<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改临床招募')" />
    <th:block th:include="include :: datetimepicker-css"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: summernote-css"/>
    <th:block th:include="include :: jquery-smartwizard-css"/>
    <th:block th:include="include :: select2-css"/>
    <th:block th:include="include :: bootstrap-select-css"/>
    <th:block th:include="include :: summernote-css"/>

</head>
<script src="../static/js/xm-select.js" th:src="@{/js/xm-select.js}"></script>

<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-clinical-edit" th:object="${clinical}">
        <ul class="nav nav-tabs">
            <li class="active"><a data-toggle="tab" href="#tab-1" aria-expanded="true">基本信息</a>
            </li>
            <li class=""><a data-toggle="tab" href="#tab-2" aria-expanded="false">临床招募TDK</a>
            </li>
        </ul>
        <div class="tab-content">
            <input name="id" th:field="*{id}" type="hidden">
            <div id="tab-1" class="tab-pane active" style="padding: 20px">

                <div class="form-group">
                    <div class="col-sm-6">
                        <label class="col-sm-2 control-label">短标题</label>
                        <div class="col-sm-10">
                            <input name="title" class="form-control" type="text" th:field="*{title}">
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <label class="col-sm-2 control-label">适应症</label>
                        <div class="col-sm-10">
                            <input name="indications" class="form-control" th:field="*{indications}">
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-6">
                        <label class="col-sm-2 control-label">招募阶段</label>
                        <div class="col-sm-10">
                            <select name="stage" class="form-control m-b" th:with="type=${@dict.getType('recruitment_stage')}">
                                <option value="">请选择招募阶段</option>
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}" th:field="*{stage}"></option>
                            </select>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <label class="col-sm-2 control-label">性别类型</label>
                        <div class="col-sm-10">
                            <select name="sexType" class="form-control m-b" >
                                <option value="" th:field="*{sexType}">请选择性别类型</option>
                                <option value="0" th:field="*{sexType}">女</option>
                                <option value="1" th:field="*{sexType}">男</option>
                                <option value="2" th:field="*{sexType}">男女不限</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-6">
                        <label class="col-sm-2 control-label">试验分期</label>
                        <div class="col-sm-10">
                            <div id="trialSelect"></div>
                        </div>
                    </div>

                    <div class="col-sm-6">
                        <label class="col-sm-2 control-label">药品名称</label>
                        <div class="col-sm-10">
                            <input name="drug" class="form-control" th:value="*{drug}">
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-6">
                        <label class="col-sm-2 control-label">年龄</label>
                        <div class="col-sm-10">
                            <input name="age" class="form-control" type="number" th:value="*{age}">
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <label class="col-sm-2 control-label">登记号</label>
                        <div class="col-sm-10">
                            <input name="registrationNum" class="form-control" th:value="*{registrationNum}">
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-6">
                        <label class="col-sm-2 control-label">人数</label>
                        <div class="col-sm-10">
                            <input name="peopleNum" class="form-control" type="number" th:value="*{peopleNum}">
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <label class="col-sm-2 control-label">起始时间</label>
                        <div class="input-group date">
                            <input type="text" class="input-sm form-control" style="border-radius: 6px 0px 0px 6px !important" id="startTime" name="startTime" placeholder="开始时间" th:value="${#dates.format(clinical.startTime,'yyyy-MM-dd')}"/>
                            <span class="input-group-addon" style="border-left: 0px solid;border-right: 0px solid;">到</span>
                            <input type="text" class="input-sm form-control" style="border-radius: 0px 6px 6px 0px !important" id="endTime" name="endTime" placeholder="结束时间"  th:value="${#dates.format(clinical.endTime,'yyyy-MM-dd')}"/>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-6">
                        <label class="col-sm-2 control-label">选择疾病</label>
                        <div class="col-sm-10">
                            <div id="selectDemo"></div>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <label class="col-sm-2 control-label is-required">治疗阶段</label>
                        <div class="col-sm-10">
                            <select name="treatmentStage" class="form-control m-b"
                                    th:with="type=${@dict.getType('treatment_stage')}" required data-placeholder="请选择治疗阶段"  onchange="changeTreatmentStageId()" id="treatmentStageId">
                                <option value="">&ensp;请选择治疗阶段</option>
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}"
                                        th:value="${dict.dictValue}" th:field="*{treatmentStage}"></option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-12">
                        <label class="col-sm-1 control-label is-required">试验中心</label>
                        <div class="col-sm-11" th:with="type=${@dict.getType('provinces_code')}">
                            <label th:each="dict : ${type}" class="check-box">
                                <input name="trialArea" type="checkbox" th:value="${dict.dictValue}" th:text="${dict.dictLabel}"
                                       th:attr="checked=${#lists.contains(#strings.listSplit(clinical.trialArea != null ? clinical.trialArea : '',','),dict.dictValue)}" >
                                <div style="display: none">
                                    <input name="areaName" type="checkbox" th:value="${dict.dictLabel}" th:text="${dict.dictLabel}"
                                           th:attr="checked=${#lists.contains(#strings.listSplit(clinical.trialArea != null ? clinical.trialArea : '',','),dict.dictValue)}" style="display:none">
                                </div>
                            </label>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-12">
                        <label class="col-sm-1 control-label">项目介绍</label>
                        <div class="col-sm-11">
                            <input type="hidden" class="form-control" required>
                            <script id="content" name="content" type="text/plain"></script>
                        </div>
                    </div>
                </div>

<!--                <div class="form-group">-->
<!--                    <div class="col-sm-12">-->
<!--                        <label class="col-sm-1 control-label">入选条件</label>-->
<!--                        <div class="col-sm-11">-->
<!--                            <input type="hidden" class="form-control" required>-->
<!--                            <script id="selected" name="selected" type="text/plain"></script>-->
<!--                        </div>-->
<!--                    </div>-->
<!--                </div>-->

<!--                <div class="form-group">-->
<!--                    <div class="col-sm-12">-->
<!--                        <label class="col-sm-1 control-label">排除条件</label>-->
<!--                        <div class="col-sm-11">-->
<!--                            <input type="hidden" class="form-control" required>-->
<!--                            <script id="exclusion" name="exclusion" type="text/plain"></script>-->
<!--                        </div>-->
<!--                    </div>-->
<!--                </div>-->

            </div>
            <div id="tab-2" class="tab-pane " style="padding: 20px">
                <div class="form-group">
                    <label class="col-sm-2 control-label">临床招募标题</label>
                    <div class="col-sm-10">
                        <input name="webtitle" class="form-control" placeholder="请输入标题" type="text" th:value="*{webtitle}">
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">临床招募关键词</label>
                    <div class="col-sm-10">
                        <input name="keywords" class="form-control" placeholder="请输入关键词" type="text" th:value="*{keywords}">
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">临床招募描述</label>
                    <div class="col-sm-10">
                        <input name="description" class="form-control" placeholder="请输入描述" type="text" th:value="*{description}">
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">临床招募说明</label>
                    <div class="col-sm-10">
                        <input name="tdkTitle" class="form-control" placeholder="请输入说明" type="text" th:value="*{tdkTitle}">
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">临床招募内容</label>
                    <div class="col-sm-10">
                        <input type="hidden" class="form-control" required>
                        <script id="tdkDescribe" name="tdkDescribe" type="text/plain"></script>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<th:block th:include="include :: footer"/>
<th:block th:include="include :: datetimepicker-js"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>
<th:block th:include="include :: summernote-js"/>
<th:block th:include="include :: jquery-smartwizard-js"/>
<th:block th:include="include :: select2-js"/>
<th:block th:include="include :: bootstrap-select-js"/>
<th:block th:include="include :: summernote-js"/>
<script src="/ueditor/ueditor.config.js" type="text/javascript" charSet="utf-8"></script>
<script src="/ueditor/ueditor.all.js" type="text/javascript" charSet="utf-8"></script>
<script src="/ueditor/lang/zh-cn/zh-cn.js" type="text/javascript" charSet="utf-8"></script>
<script th:inline="javascript">
    var selectData = [];
    var trialData = [];
    var backdis = [];
    var backFactory = [];
    var disarr = [];
    var trialArr = [];
    var diseasearr = [[${clinical}]].diseaseList
    var trialarr = [[${clinical}]].trialStaging
    var trialnamearr = [[${clinical}]].trialName
    var prefix = ctx + "ydz/clinical"
    $("#form-clinical-edit").validate({
        focusCleanup: true
    });
    function remove(e) {
        $(e).parent().remove();
    }

    //初始化加载
    $(document).ready(function () {
        parent.$('body').find('.layui-layer-max:not(.layui-layer-maxmin)').click()

        //回显疾病多选
        if (null != diseasearr){
            diseasearr.forEach(item=>{
                let obj = {}
                obj.diseaseId =item.diseaseId
                obj.pid = item.pid
                disarr.push(obj)
                backdis.push(item.diseaseId.toString())
            })
        }
        //实验分期多选
        if(trialarr != null){
            var triallist = trialarr.split(",")
            var trialnamelist = trialnamearr.split(",")
            $.each(triallist, function(i, value) {
                let obj = {
                    dictLabel:trialnamelist[i],
                    dictValue:triallist[i]
                }
                trialArr.push(obj);
                backFactory.push(value);
            });
        }

        //加载疾病下拉
        $.ajax({
            url: "/api/common/selectNewDisease",
            type: "get",
            success: res => {
                alldis = res.data
                for (let i = 0; i < alldis.length; i++){
                    let val = {}
                    val.name = alldis[i].name
                    val.diseaseId = alldis[i].id
                    val.pid = alldis[i].pid
                    selectData.push(val)
                }
                initXmSelect()
            }
        })
        //加载试验分期下拉
        $.ajax({
            url: "/api/common/getDictByType/trial_staging",
            type: "get",
            success: res => {
                var trialList = res.data
                for (let i = 0; i < trialList.length; i++){
                    let val = {}
                    val.dictLabel = trialList[i].dictLabel
                    val.dictValue = trialList[i].dictValue
                    trialData.push(val)
                }
                trialSelect()
            }
        })
    })

    //疾病多选
    function initXmSelect(){
        xmSelect.render({
            el: '#selectDemo',
            checkbox: true,
            repeat: false,
            autoRow: true,
            filterable: true,
            prop: {name: 'name', value: 'diseaseId',pid:'pid'},
            initValue: backdis,//回显
            height: '200px',
            tips: '请选择',
            tree: {
                show: true,
                showFolderIcon: true,
                showLine: true,
                indent: 20,
                expandedKeys: [-3],
                strict: false,
            },
            data: function () {
                return selectData
            },
            on: function (data) {
                disarr = data.arr;//arr:  当前多选已选中的数据
            },
        });
    }

    //点击添加按钮
    function submitHandler() {
        if ($.validate.form()) {
            var jsons = {};
            let formData = $('#form-clinical-edit').serializeArray();

            // 试验中心字符串
            let arealist = ''
            $.each(formData, function (k, v) {
                if(v.name != 'trialArea'){
                    jsons[v.name] = v.value;
                }else{
                    arealist += v.value + ','
                }
            });
            if(arealist.length > 0){
                arealist = arealist.slice(0, -1);
            }
            jsons["trialArea"] = arealist

            //疾病数组
            jsons["diseaseList"] = disarr;
            //厂家id、名称格式化拼接
            jsons["trialStaging"] = getManuIdOpt(trialArr);
            jsons["trialName"] = getManuNameOpt(trialArr);
            //其他tdk
            // var clinicalTdk={}
            // clinicalTdk.webtitle = $("input[name='webtitle']").val();
            // clinicalTdk.description = $("input[name='description']").val();
            // clinicalTdk.keywords = $("input[name='keywords']").val();
            // clinicalTdk.tdkTitle = $("input[name='tdkTitle']").val();
            // clinicalTdk.tdkDescribe = tdkDescribe.getContentTxt()
            // jsons["clinicalTdk"] = clinicalTdk;
            var value = JSON.stringify(jsons)
            save(prefix + "/edit", value);
        }
    }

    function changeTreatmentStageId(){
        let errorValue = $('#treatmentStageId').val()
            if (errorValue != "") {
                $("#treatmentStageId-error").removeClass("error")
            } else {
                return
            }
        }

    //格式化实验分期id 拼接成“,”分割的字符串
    function getManuIdOpt(arr) {
        var str = "";
        arr.forEach(item=>{
            str += item.dictValue+",";
        });
        //去掉最后一个逗号(如果不需要去掉，就不用写)
        if (str.length > 0) {
            str = str.substring(0,str.length - 1);
        }
        return str;
    }

    //格式化厂家名称 拼接成“,”分割的字符串
    function getManuNameOpt(arr) {
        var str = "";
        arr.forEach(item=>{
            str += item.dictLabel+",";
        });
        //去掉最后一个逗号(如果不需要去掉，就不用写)
        if (str.length > 0) {
            str = str.substring(0,str.length - 1);
        }
        return str;
    }

    //实验分期多选
    function trialSelect(){
        xmSelect.render({
            el: '#trialSelect',
            checkbox: true,
            repeat: false,
            autoRow: true,
            filterable: true,
            prop: {name: 'dictLabel', value: 'dictValue'},
            initValue: backFactory,//回显
            height: '200px',
            tips: '请选择',
            tree: {
                show: true,
                showFolderIcon: true,
                showLine: true,
                indent: 20,
                expandedKeys: [-3],
                strict: false,
            },
            data: function () {
                return trialData
            },
            on: function (data) {
                trialArr = data.arr;//arr:  当前多选已选中的数据
                //factoryArr = data.arr
            },
        });
    }

    //json请求
    function save(url, data, callback) {
        var config = {
            url: url,
            type: "post",
            dataType: "json",
            data: data,
            headers: {
                'Content-Type': 'application/json;charset=utf8'
            },
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍候...");
                $.modal.disable();
            },
            success: function (result) {
                if (typeof callback == "function") {
                    callback(result);
                }
                $.operate.successCallback(result);
            }
        };
        $.ajax(config)
    }

    // 多图上传
    $(".files-upload").fileinput({
        uploadUrl: ctx + 'common/uploads',
        allowedFileTypes: ['image'],
        maxFileCount: 5,
        autoReplace: false,
        uploadAsync: false
    }).on('filebatchuploadsuccess', function (event, data, previewId, index) {
        var rsp = data.response;
        let val = $("input[name='" + event.currentTarget.id + "']").val()
        if (val) {
            val += ','
        }
        console.log(event.currentTarget,event.currentTarget);
        $("input[name='" + event.currentTarget.id + "']").val(val + rsp.fileNames)
    }).on('fileremoved', function (event, id, index) {
        $("input[name='" + event.currentTarget.id + "']").val('')
    })

    //富文本
    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
    UE.Editor.prototype.getActionUrl = function (action) {
        if (action == 'uploadimage' || action == 'uploadscrawl') {
            return '/common/upload';
        } else {
            return this._bkGetActionUrl.call(this, action);
        }
    }

    var announcements = UE.getEditor('announcements', {
        autoHeightEnabled: false,//是否自动长高
        autoFloatEnabled: true,//是否保持toolbar的位置不动
        scaleEnabled: true,//是否可以拉伸长高
        initialFrameWidth: 'auto',//初始化编辑器宽度
        initialFrameHeight: 300,//初始化编辑器高度
    });

    var content = UE.getEditor('content', {
        autoHeightEnabled: false,//是否自动长高
        autoFloatEnabled: true,//是否保持toolbar的位置不动
        scaleEnabled: true,//是否可以拉伸长高
        initialFrameWidth: 'auto',//初始化编辑器宽度
        initialFrameHeight: 300,//初始化编辑器高度
    });
    content.ready(function () {
        content.execCommand("insertHtml", [[${clinical}]].content);//富文本回显
    })
    var selected = UE.getEditor('selected', {
        autoHeightEnabled: false,//是否自动长高
        autoFloatEnabled: true,//是否保持toolbar的位置不动
        scaleEnabled: true,//是否可以拉伸长高
        initialFrameWidth: 'auto',//初始化编辑器宽度
        initialFrameHeight: 300,//初始化编辑器高度
    });
    selected.ready(function () {
        selected.execCommand("insertHtml", [[${clinical}]].selected);//富文本回显
    })
    var exclusion = UE.getEditor('exclusion', {
        autoHeightEnabled: false,//是否自动长高
        autoFloatEnabled: true,//是否保持toolbar的位置不动
        scaleEnabled: true,//是否可以拉伸长高
        initialFrameWidth: 'auto',//初始化编辑器宽度
        initialFrameHeight: 300,//初始化编辑器高度
    });
    exclusion.ready(function () {
        exclusion.execCommand("insertHtml", [[${clinical}]].exclusion);//富文本回显
    })

    var tdkDescribe = UE.getEditor('tdkDescribe', {
        autoHeightEnabled: false,//是否自动长高
        autoFloatEnabled: true,//是否保持toolbar的位置不动
        scaleEnabled: true,//是否可以拉伸长高
        initialFrameWidth: 'auto',//初始化编辑器宽度
        initialFrameHeight: 300,//初始化编辑器高度
    });
    tdkDescribe.ready(function () {
        tdkDescribe.execCommand("insertHtml", [[${clinical}]].tdkDescribe);//富文本回显
    })

    $("input[name='startTime']").datetimepicker({
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true
    });

    $("input[name='endTime']").datetimepicker({
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true
    });

    $(".file-upload").fileinput({
        uploadUrl: ctx + 'common/upload',
        maxFileCount: 1,
        autoReplace: true
    }).on('fileuploaded', function (event, data, previewId, index) {
        $("input[name='" + event.currentTarget.id + "']").val(data.response.fileName)
    }).on('fileremoved', function (event, id, index) {
        $("input[name='" + event.currentTarget.id + "']").val('')
    })

    // 去除疾病error提示
    function changeError() {
        let errorValue = $('#cid').val()
        if (errorValue != "") {
            $("#cid-error").removeClass("error").addClass("remove-error")
        } else {
            return
        }

    }
</script>
</body>
</html>